/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.guide.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.CacheUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.guide.entity.MobileMaterial;
import com.jeeplus.modules.guide.entity.YmbcsMatterBszn;
import com.jeeplus.modules.guide.service.*;
import com.jeeplus.modules.guide.utils.*;
import com.jeeplus.modules.sys.entity.MobileUserQR;
import com.jeeplus.modules.sys.utils.EncryptUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.*;
import java.util.*;

/**
 * 高新智能导办-事项分类，情形话，材料相关获取功能
 * 事项Controller
 * @author azj
 * @version 2021-5-15
 */
@RestController
@RequestMapping("/indexMatter")
@RequiredArgsConstructor
public class MobileIndexController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(MobileIndexController.class);
	private final MobileIndexService mobileIndexService;
	private final MatterUtils matterUtils;
	private final VersionService versionService;
	private final  MobileBusinessService mobileBusinessService;
	private final MobileItemService mobileItemService;
	private final WeixinUtil weixinUtil;
	private final MobileMatterService mobileMatterService;
	private final HisQueueService hisQueueService;
	private final MobileQueueService mobileQueueService;
	private final YmbcsMatterService ymbcsMatterService;
	private final PolicyService policyService;
	//合作街道organOid
	@Value("${matterOrganOid}")
	private String matterOrganOid;
	/**
	 * getMatterValue 获取热门事项加载 热门top5事项
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value ="getMatterTop")
	public AjaxJson getMatterTop() {
		List<Map<String, Object>> matterTop = mobileIndexService.getMatterTop(versionService.getVersion());
		for(Map<String, Object> m : matterTop){
			if(m.get("organOid").equals(matterOrganOid)){
				m.put("matterName",m.get("matterName")+"(街道)");
			}
		}
		return AjaxJson.success("热门事项加载成功！").put("data", matterTop);
	}

	/**
	 * getMatterValue 通过标签加载事项
	 * label标签名称
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value ="findMatterList")
	public AjaxJson findMatterList(String label) {
		if(StringUtils.isNotBlank(label) && label.length() >= 2){
			mobileItemService.intoLabelHistory(label);
		}
		label = "%" + label + "%";
		List<Map<String, Object>> matterList = mobileIndexService.findMatterList(label, versionService.getVersion());
		for(Map<String, Object> m : matterList){
			if(m.get("organOid").equals(matterOrganOid)){
				m.put("matterName",m.get("matterName")+"(街道)");
			}
		}
		return AjaxJson.success("搜索成功！").put("data", matterList);
	}

	/**
	 * findZNDBMatterList 街道智能导办事项加载事项
	 * label标签名称
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value ="findZNDBMatterList")
	public AjaxJson findZNDBMatterList(String label) {
		return AjaxJson.success("搜索成功！").put("data", mobileIndexService.findZNDBMatterList(label, versionService.getVersion()));
	}


	/**
	 * 事项情形化加载
	 * oid事项id
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value ="findSisutionValue")
	public AjaxJson findSisutionValue(String oid) {
		return AjaxJson.success("事项情形化加载成功！").put("data", matterUtils.findSisutionValue(oid));

	}
	/**
	 * getMatterBSZN 获取事项办事指南
	 * oid事项id
	 * ids情形话选择id集合
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value ="getMatterBSZN")
				public AjaxJson getMatterBSZN(String oid,String ids,String otherVersion) {
					List<MobileMaterial> list = null;
		            List<String> valuesStr = new ArrayList<String>();
		            Map<String,Object> values = mobileIndexService.getMatterBSZN(oid,versionService.getVersion(),otherVersion);
		            int valueSize = 0;
		            if(null != values){
						List<Map<String,String>> map = mobileQueueService.getCloseValue();
						JSONArray json = null;
						if(StringUtils.isNotBlank(mobileIndexService.findIsStree(versionService.getVersion(),oid))){
							values.put("organName","街道办事处");
							json = new JSONArray();
							List<YmbcsMatterBszn> listValue = ymbcsMatterService.ymbcsStreeList(mobileIndexService.getMatterName(versionService.getVersion(),oid),versionService.getVersion());
							valueSize = listValue.size();
							if(valueSize >= 2)json.add("各街道综合便民服务中心");
							for(int i =0;i<valueSize;i++){
								if(valueSize >= 2){
									valuesStr.add((i+1)+"、"+listValue.get(i).getOrganName()+":"+listValue.get(i).getZxDhText());
								} else{
									valuesStr.add(listValue.get(i).getOrganName()+":"+listValue.get(i).getZxDhText());
									json.addAll(JSONArray.parseArray(listValue.get(i).getLocationAddr()));
								}

							}
							values.put("telList",valuesStr);
						}else{
							json = JSONArray.parseArray(values.get("locationAddr").toString());
							valuesStr.add(values.get("zxDhText")+"");
							values.put("telList",valuesStr);
						}
						valueSize = json.size();
						if(!map.isEmpty()){
							String address = "";
							for(Map<String,String> m : map){
								if(null != m.get("address")){
									address += m.get("address")+"-";
								}
							}
							for(int i =0;i< valueSize;i++){
								if(address.contains(json.getString(i))){
									json.remove(i);
								}
						}
							if(json.size() == 0){
								json.add("该办理地址临时关闭！");
							}
					}
						if(valueSize >= 2){
							String jsonValues = "";
							for(int k =0;k< valueSize;k++){
								jsonValues = json.getString(k);
								json.remove(k);
								json.add(k,(k+1)+"、"+jsonValues);
							}
						}
						values.put("locationAddr",json);
		            }

					if(StringUtils.isNotBlank(ids)){
						try{
							JSONObject js = matterUtils.getMaterialValue(ids);
							if("200".equals(js.getString("code")) && StringUtils.isNotBlank(js.getString("data"))){
								list = JSONArray.parseArray(js.getString("data"), MobileMaterial.class);
								for(MobileMaterial mm : list){
									if(StringUtils.isBlank(mm.getMaterialName())){
										mm.setMaterialName(mm.getRawMaterialName());
									}
									mm.setMaterialName(mm.getMaterialName()+"("+mm.getRawSource()+"/"+mm.getRawPaperNumber()+"份/"+mm.getRawMaterialType()+")");
								}
							}
							return AjaxJson.success("事项办事指南加载成功！").put("matter", values).put("data",list);
			}catch(Exception e){
				log.error(e.getMessage());
				log.error("获取事项办事指南失败！oid:"+oid);
				return AjaxJson.error("获取事项办事指南失败！");
			}
		}else{
			try{
				String result = mobileIndexService.getMatterMaterialList(oid,versionService.getVersion());
				if(StringUtils.isNotBlank(result)){
					list = JSONArray.parseArray(result, MobileMaterial.class);
					for(MobileMaterial mm : list){
						if(StringUtils.isBlank(mm.getMaterialName())){
							mm.setMaterialName(mm.getRawMaterialName());
						}
						mm.setMaterialName(mm.getMaterialName()+"("+mm.getRawSource()+"/"+mm.getRawPaperNumber()+"份/"+mm.getRawMaterialType()+")");
					}
				}
				return AjaxJson.success("事项办事指南加载成功！").put("matter", values).put("data",list);
			}catch(Exception e){
				log.error(e.getMessage());
				e.printStackTrace();
				log.error("获取事项办事指南失败！oid:"+oid);
				return AjaxJson.error("获取办事指南失败！");
			}
		}
	}


	/**
	 * 获取事项部门
	 * getMatterManger
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getMatterManger")
	public AjaxJson getMatterManger (){
		return AjaxJson.success().put("data",mobileIndexService.getMatterManger(versionService.getVersion()));
	}


	/**
	 * 获取事项部门事项
	 * getMatterMaterialList
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getMatterMangerList")
	public AjaxJson getMatterMangerList(String organName){
		if(organName.contains("街道办事处")) return AjaxJson.success().put("data",mobileIndexService.getMatterStreeList(versionService.getVersion(),organName));
		else return AjaxJson.success().put("data",mobileIndexService.getMatterMangerList(versionService.getVersion(),organName));
	}


	/**
	 * 获取事项层级
	 * getMatterLevel
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getMatterLevel")
	public AjaxJson getMatterLevel (){
		return AjaxJson.success().put("data",mobileIndexService.getMatterLevel(versionService.getVersion()));
	}

	/**
	 * 获取事项层级事项集合
	 * getMatterLevelList
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getMatterLevelList")
	public AjaxJson getMatterLevelList (String areaType){
		return AjaxJson.success().put("data",mobileIndexService.getMatterLevelList(versionService.getVersion(),areaType));
	}

	/**
	 * 获取热点事项
	 * getMatterLevelList
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getMatterTopList")
	public AjaxJson getMatterTopList (){
		List<Map<String, String>> matterTopList = mobileIndexService.getMatterTopList(versionService.getVersion());
		for(Map<String, String> m : matterTopList){
			if(m.get("organOid").equals(matterOrganOid)){
				m.put("matterName",m.get("matterName")+"(街道)");
			}
		}
		return AjaxJson.success().put("data",matterTopList);
	}

	/**
	 * 获取事项材料下载/预览
	 *getMatterFile
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value ="getMatterFile")
	public AjaxJson getMatterFile(String attaOid) {
		return matterUtils.getMatterFile(attaOid);
	}



	/**
	 * 获取一页一证
	 * getOneThing
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getOneThing")
	public AjaxJson getOneThing (){
		return AjaxJson.success().put("data",matterUtils.getOneThing());
	}


	/**
	 * 获取一页一证事项详细信息
	 * oid一页一证id
	 * getThingValue
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getThingValue")
	public AjaxJson getThingValue (String oid,String ids,String titleIds){
		Object obj = null;
		if(StringUtils.isNotBlank(ids)){
			obj = matterUtils.getThingSisutionMatterUtils(oid,ids,titleIds);
		}
		return AjaxJson.success().put("data",matterUtils.getThingValue(oid)).put("thingMaterial",obj);
	}

	/**
	 * 一页一证事项情形化
	 * * oid一页一证id
	 * getThingSisution
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getThingSisution")
	public AjaxJson getThingSisution (String oid){
		return AjaxJson.success().put("data",matterUtils.getThingSisution(oid));
	}

	/**
	 * getMatterFile 获取一页一证材料下载/预览
	 * attaOid材料id
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value ="getThingFile")
	public AjaxJson getThingFile(String attaOid) {
		return matterUtils.getThingFile(attaOid);
	}


	/**
	 * 事项名称
	 * oid事项id
	 * getMatterName
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getMatterName")
	public AjaxJson getMatterName (String oid){
		return AjaxJson.success().put("data",mobileIndexService.getMatterName(versionService.getVersion(),oid));
	}

	/**
	 * 主题事项加载
	 * itemName主题名称
	 * getMatterItem
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getMatterItemBySubject")
	public AjaxJson getMatterItemBySubject (@ApiParam(name = "serviceSubject", value = "主题分类:1是企业开办，2是社会事务，3是税务，4是社保，5是医保，6是工程建设，7是公安户政，8是出入境，9是婚姻登记，10是不动产，11是人才服务", required = true)@RequestParam("serviceSubject")String serviceSubject){
		if("12".equals(serviceSubject)){
			return AjaxJson.success().put("data",mobileIndexService.getMatterItemOther());
		}
		List<Map<String, String>> matterItem = mobileIndexService.getMatterItem(serviceSubject, null, versionService.getVersion());
		for(Map<String, String> m : matterItem){
			if(m.get("organOid").equals(matterOrganOid)){
				m.put("matterName",m.get("matterName")+"(街道)");
			}
		}
		return AjaxJson.success().put("data",matterItem);
	}
	/**
	 * 生命周期事项加载
	 * itemName主题名称
	 * getMatterItem
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getMatterItemByLifeCycle")
	public AjaxJson getMatterItemByLifeCycle (@ApiParam(name = "serviceLifeCycle", value = "自然人 11是出生，12是入学，13是落户，14是就业，15是结婚，16是生育，17是就医，18是死亡 ;法人 21是登记，22是变更，23是注销", required = true)@RequestParam("serviceLifeCycle")String serviceLifeCycle){
		return AjaxJson.success().put("data",mobileIndexService.getMatterItem(null,serviceLifeCycle,versionService.getVersion()));
	}

	/**
	 * 点位获取 参数为空获取全部，多个用,隔开
	 * orgrizeStatusValue点位集合字符串
	 * findAddrList
	 * @return 受影响的行数
	 */
	@GetMapping(value ="findAddrList")
	public AjaxJson findAddrList(String orgrizeStatusValue,String pageNo,String pageSize){
		return AjaxJson.success().put("data",mobileBusinessService.findAddrList(orgrizeStatusValue,pageNo,pageSize));
	}

	/**
	 * 点位获取事项
	 * areaId点位标识
	 * findAddrMatterList
	 * @return 受影响的行数
	 */
	@GetMapping(value ="findAddrMatterList")
	public AjaxJson findAddrMatterList(String areaId){
		return AjaxJson.success().put("data",mobileIndexService.findAddrMatterList(areaId,versionService.getVersion()));
	}

	/**
	 * listAreaTypeValue 获取区域集合
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value ="listAreaTypeValue")
	public AjaxJson listAreaTypeValue() {
		return AjaxJson.success().put("data",mobileBusinessService.listAreaType());
	}


	/**
	 * 老人版/英文版事项加载
	 * getMatterOldOrEN
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getMatterOldOrEN")
	public AjaxJson getMatterOldOrEN (@ApiParam(name = "serviceOldAndEN", value = "主题分类:1是老人版，2是英文版", required = true)@RequestParam("serviceOldAndEN")String serviceOldAndEN){
		if(StringUtils.isNotBlank(serviceOldAndEN) && ("1".equals(serviceOldAndEN) || "2".equals(serviceOldAndEN))){
			return AjaxJson.success().put("data",mobileIndexService.getMatterOldOrEN(serviceOldAndEN,versionService.getVersion()));
		}else{
			return AjaxJson.error("无效参数！").put("code",400).put("data",null);
		}
	}

	/**
	 * 除长者版外所有事项加载
	 * getOutMatterEN
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getOutMatterEN")
	public AjaxJson getOutMatterEN (int pageNo,int pageSize){
		Map<String,Object> map = new HashMap<>();
		map.put("curPage",pageNo);
		map.put("pageSize",pageSize);
		map.put("version",versionService.getVersion());
		return AjaxJson.success("事项加载成功！").put("data", mobileMatterService.getOutMatterEN(map));
	}

	/**
	 * 获取当前TokenValue
	 * getTokenValue
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getTokenValue")
	public AjaxJson getTokenValue (){
		return AjaxJson.success().put("token",CacheUtils.get(WeixinUtil.TOKEN_CACHE, "token"));
	}

	/**
	 * 更新当前TokenValue
	 * updateTokenValue
	 * @return 受影响的行数
	 */
	@GetMapping(value ="updateTokenValue")
	public AjaxJson updateTokenValue (){
		weixinUtil.getAccessToken();
		return AjaxJson.success();
	}

	/**
	 * 判断是否事项绑定点位isHasArea
	 * oid 事项id
	 * @return 受影响的行数
	 */
	@GetMapping(value ="isHasArea")
	public AjaxJson isHasArea (String oid){
		if(StringUtils.isNotBlank(mobileIndexService.findMatterManager(oid,versionService.getVersion()))){
			return AjaxJson.success().put("isHasArea",true).put("isBDC",true);
		}else{
			if(mobileIndexService.isHasArea(oid) >= 1){
				return AjaxJson.success().put("isHasArea",true);
			}else{
				return AjaxJson.error("暂无此事项点位配置").put("isHasArea",false);
			}
		}
	}

	/**
	 * h获取业务名称
	 * oid 事项id
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getTypeNameValue")
	public AjaxJson getTypeNameValue (String businessId){
		return AjaxJson.success().put("nameValue",hisQueueService.getTypeNameValue(businessId));
	}

	@GetMapping(value ="isDoTime")
	public AjaxJson isDoTime() {
		return AjaxJson.success("操作成功！").put("isDo",mobileMatterService.isDoTime());
	}

	@GetMapping(value ="checkDoTime")
	public AjaxJson checkDoTime(String typeId) {
		return AjaxJson.success("操作成功！").put("isDo",mobileQueueService.findDoTime(typeId));
	}

	@GetMapping(value ="streetList")
	public Object streetList(){
		return matterUtils.streetList();
	}

	@GetMapping(value ="getCompanyCode")
	public Object getCompanyCode(String companyCode,HttpServletRequest request)throws SocketException {
		return matterUtils.getCompanyCode(companyCode);
	}

	@GetMapping(value ="mapOfficesList")
	public AjaxJson mapOfficesList(){
		return AjaxJson.success().put("data",mobileIndexService.mapOfficesList());
	}

	@GetMapping(value ="findPolicy")
	public AjaxJson findPolicy(){
		return AjaxJson.success().put("data",policyService.findPolicy());
	}


}
